<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 *
 * @abstract 产品API
 * @author zxj
 *
 */
class Products extends CI_Controller
{
    private $t_product = 'mt_product';

    function __construct()
    {
        parent::__construct();
    }


    /**
     * 产品列表
     */
    function index()
    {
        //输出数据结构
        $status = 0;
        $gpData = $formData = gp();  // get post data
        //获取表字段(即查询条件,时间查询额外处理)
        $fieldsList = $this->db->list_fields($this->t_product);
        $fieldsOrder = array('delivery_country', 'point','source_oid','shipinTrack','shipoutTrack');
        array_push($fieldsList, 'startTime', 'endTime');
        $fieldsList = array_merge($fieldsList, $fieldsOrder);
        //允许模糊搜索的字段
        $fieldsLike = array('imei','source_oid','shipinTrack','shipoutTrack');
        //接受参数
        $where = '';
        //拼接查询字符串
        foreach ($formData as $key => $val) {
            $val = trim($val);
            if (!$val || !in_array($key, $fieldsList)) continue;
            if ($key == 'startTime' || $key == 'endTime') {
                if ($key == 'startTime') {
                    $where .= 'b.create_time >=\'' . $val . ' 00:00:00\'';
                }
                if ($key == 'endTime') {
                    $where .= 'b.create_time <=\'' . $val . ' 23:59:59\'';
                }
            } elseif (in_array($key, $fieldsOrder)) {
                $where .= in_array($key, $fieldsLike) ? "b.{$key} like '%{$val}%'" : "b.{$key}='{$val}'";
            } else {
                $where .= in_array($key, $fieldsLike) ? "a.{$key} like '%{$val}%'" : "a.{$key}='{$val}'";
            }
            $where .= ' and ';
        }
        $where = $where ? ' where ' . rtrim($where, ' and ') : '';
        //#分页
        $page = (int)$gpData['page'];
        $pagesize = (int)$gpData['pagesize'];
        $page = max($page, 1);
        $pagesize = empty($pagesize) ? $pagesize = 20 : $pagesize;
        $offset = ($page - 1) * $pagesize; //显示偏移

        $fields = 'a.id,a.oid,a.order_num,a.status_id,a.productSku,a.product_brand,a.brandCustomerNum,a.product_model,a.imei,
            b.source_oid,b.shipinTrack,b.shipoutTrack,
            b.service_center,b.service_type,b.product_quantity,b.merchant_num,b.consumer_num,b.add_user,b.create_time,
            b.orderSubtotalBrand,b.grandTotalBrand,b.delivery_country,b.currency_code as `currency`';

        $sql = "
            select 
                __fields__
            from 
                mt_product a 
                left join mt_order b on a.oid = b.id 
            {$where}";
        // 总记录数及页数
        $query = $this->db->query(str_replace('__fields__', 'count(a.id) `rows`', $sql));
        $row = $query->row_array();
        $total_rows = $row['rows'];
        $pagecount = ceil($total_rows / $pagesize); //总页数
        //查询返回的数组
        $sql .= ' order by b.create_time desc limit ' . $offset . ',' . $pagesize . ' ';
        $dataList = $this->common_model->getQuery(str_replace('__fields__', $fields, $sql), 'result_array');
        //重构数据
        foreach ($dataList as $key => &$rs) {
            //$serviceCenter = $this->common_model->selectFirst('mt_service_center', array('id' => $rs['service_center']));
            //$rs['country_name'] = $serviceCenter['name_en'];
            $statusFirst = $this->common_model->selectFirst('mt_product_status', array('id' => $rs['status_id']));
            $countryFirst = $this->common_model->selectFirst('mt_country', array('iso' => $rs['delivery_country']));
            $rs['delivery_country'] = $countryFirst['nombre'];
            $rs['statusName'] = $statusFirst['name_en'];
            $rs['statusName_ch'] = $statusFirst['name_ch'];
        }
        unset($rs);
        //构造data数组
        $data = array(
            'page' => $page,
            'pagesize' => $pagesize,
            'pagecount' => $pagecount,
            'totalrows' => $total_rows,
            'dataList' => $dataList
        );
        //json判断处理
        if (empty($dataList)) {
            $message = 'No more data!';
        } else {
            $message = 'return succeed!';
            $status = 1;
        }
        json_output($data, $message, $status);
    }


    /**
     * 获取单个产品信息
     */
    function get_product_one()
    {
        //判断处理输出
        $data = array();
        //接受产品ID
        $id = (int)$this->input->get_post('id');
        //产品信息
        $productFirst = $this->common_model->selectFirst($this->t_product, array('id' => $id));
        if (!$productFirst) {
            json_output($id, 'Product id can not be empty', false);
        }
        if ($productFirst['brandCustomerNum']) {
            $brandCustomer = $this->common_model->selectFirst('mt_customers', array('id' => $productFirst['brandCustomerNum']));
        }
        $productFirst['individualUserSubTotal'] = $productFirst['individualUserSubTotal'] - $productFirst['taxFee'];

        $categoryFirst = $this->common_model->selectFirst('mt_product_category', array('id' => $productFirst['category_id']));
        $statusFirst = $this->common_model->selectFirst('mt_product_status', array('id' => $productFirst['status_id']));
        $productFirst['category_name'] = $categoryFirst['name_en'];
        $productFirst['status_name'] = $statusFirst['name_en'];
        $productFirst['status_name_ch'] = $statusFirst['name_ch'];
        //获取订单信息
        $orderFirst = $this->common_model->selectFirst('mt_order', array('id' => $productFirst['oid']));
        $orderStatus = $this->common_model->selectFirst('mt_order_status', array('id' => $orderFirst['status_id']));
        $orderFirst['status_name'] = $orderStatus['name_en'];
        $orderFirst['status_name_ch'] = $orderStatus['name_ch'];
 	if ($orderFirst['merchant_num'] == '1028') {
        	$currency = $this->common_model->selectFirst('mt_product_rate', array('order_num' => $orderFirst['order_num']));
	}
        /*
        if ($orderFirst['merchant_num'] == '1028') {
            $productFirst['totalAmount'] = number_format(currency_service('USD', 'CNY', $productFirst['totalAmount'] - $productFirst['taxFee']), 2, '.', '');
        } else {
            $productFirst['totalAmount'] = $productFirst['totalAmount'] - $productFirst['taxFee'];
        }
        */
        $productFirst['totalAmount'] = $productFirst['totalAmount'] - $productFirst['taxFee'];

        //#产品成色
        if ($productFirst['physicalAppearance']) {
            $damageFirst = $this->common_model->selectFirst('mt_product_damage', array('id' => $productFirst['physicalAppearance']));
            $productFirst['damageStr'] = $damageFirst['name_en'];
            $productFirst['damageStr_ch'] = $damageFirst['name_ch'];
        }
        //#随机附件
        if ($productFirst['accessories']) {
            $accessoriesList = $this->common_model->selectCustom('mt_product_accessory', '', 'id desc', array('id' => explode(',', $productFirst['accessories'])));

            $acc_cuz = $this->common_model->selectCustom('mt_product_accessory_customize', array('category' => $productFirst['category_id'], 'merchant_id' => $orderFirst['merchant_num']));
            foreach ($accessoriesList as $k => $v) {
                foreach ($acc_cuz as $kc => $vc) {
                    if ($v['id'] == $vc['base_id']) {
                        $accessoriesList[$k]['name_ch'] = $vc['name_ch'];
                        $accessoriesList[$k]['name_en'] = $vc['name_en'];
                        break;

                    }
                }

            }

            foreach ($accessoriesList as $rs) {
                $productFirst['accessoriesStr'] .= $rs['name_en'] . ';';
                $productFirst['accessoriesStr_ch'] .= $rs['name_ch'] . ';';
            }
        }
        //#故障
        if ($productFirst['fault']) {
            $faultList = $this->common_model->selectCustom('mt_product_fault', '', 'id desc', array('id' => explode(',', $productFirst['fault'])));

            $fault_cuz = $this->common_model->selectCustom('mt_product_fault_customize', array('category' => $productFirst['category_id'], 'merchant_id' => $orderFirst['merchant_num']));
            foreach ($faultList as $k => $v) {
                foreach ($fault_cuz as $kc => $vc) {
                    if ($v['id'] == $vc['base_id']) {
                        $faultList[$k]['name_ch'] = $vc['name_ch'];
                        $faultList[$k]['name_en'] = $vc['name_en'];
                        break;

                    }
                }

            }

            foreach ($faultList as $rs) {
                $productFirst['faultStr'] .= $rs['name_en'] . ';';
                $productFirst['faultStr_ch'] .= $rs['name_ch'] . ';';
            }
        }
        //#维修项
        if ($productFirst['repairItem']) {
            $ids = explode(',', $productFirst['repairItem']);
            if ($productFirst['supplementRepairItem']) {
                $supplementIds = explode(',', $productFirst['supplementRepairItem']);
                $ids = array_merge($ids, $supplementIds);
            }
            $repairItemList = $this->common_model->selectCustom('mt_product_repair_item', '', 'grade desc', array('id' => $ids));


            //自定义维修项begin 0401
            $models = $this->common_model->selectCustom('product_model', array('sap_id' => $productFirst['model_id']));
            $sql = sprintf("select * from mt_repair_item_customize where category_id = '%s' and customer_id = '%s' and `model_id`='%s' group by `labor_id`", $productFirst['category_id'], $orderFirst['merchant_num'], $models[0]['id']);
            $acc_item = $this->db->query($sql)->result_array();
            if ($acc_item) {
                foreach ($repairItemList as $k => $v) {
                    foreach ($acc_item as $kc => $vc) {
                        if ($v['id'] == $vc['labor_id']) {
                            $repairItemList[$k]['name_ch'] = $vc['name_ch'];
                            $repairItemList[$k]['name_en'] = $vc['name_en'];
                            break;
                        }
                    }
                }
            } else {
                $sql = sprintf("select * from mt_repair_item_customize where category_id = '%s' and customer_id = '%s' and `model_id` < 0 group by `labor_id`", $productFirst['category_id'], $orderFirst['merchant_num']);
                $acc_item = $this->db->query($sql)->result_array();
                foreach ($repairItemList as $k => $v) {
                    foreach ($acc_item as $kc => $vc) {
                        if ($v['id'] == $vc['labor_id']) {
                            $repairItemList[$k]['name_ch'] = $vc['name_ch'];
                            $repairItemList[$k]['name_en'] = $vc['name_en'];
                            break;
                        }
                    }
                }
            }
            //自定义维修项end
            foreach ($repairItemList as &$rs) {
                $productFirst['repairItemStr'] .= $rs['name_en'] . ';';
                $productFirst['repairItemStr_ch'] .= $rs['name_ch'] . ';';
                //维修项价格
                $where = array('site_id' => $orderFirst['service_center'], 'labor_id' => $rs['id']);
                if ($brandCustomer['diy_price']) {
                    $priceTable = 'mt_customer_price';
                    $where['customer_id'] = $productFirst['brandCustomerNum'];
                } else {
                    $priceTable = 'mt_base_price';
                }
                $laborPrice = $this->common_model->selectFirst($priceTable, $where);
                $rs['price'] = $brandCustomer['diy_price'] ? $laborPrice['price'] : $laborPrice['brand_price'];


                //这里需要插入一个自定义的规则 sqingwen begin
                $sql = sprintf("select `price` as `laborPrice` from `mt_repair_item_customize` where `labor_id` ='" . $rs['id'] . "'  and customer_id ='" . $orderFirst['merchant_num'] . "' and  site_id='" . $orderFirst['service_center'] . "' order by id desc limit 1");
                $resultRow = $this->common_model->getQuery($sql, 'row_array');

                //如果订单是商家并且自定义项有数据，则商家去这个价格
                if (intval($orderFirst['merchant_num']) > 0 && $resultRow) {
                    $rs['price'] = $resultRow['laborPrice'];
                }
                //这里需要插入一个自定义的规则 sqingwen end


                $rs['price'] .= ' ' . $orderFirst['currency_code'];
            }
            unset($rs);
        }
        //#维修轨迹
        $trackList = $this->common_model->selectCustom('mt_product_track', array('pid' => $id), 'id desc');
        foreach ($trackList as &$rs) {
            $startStatus = $this->common_model->selectFirst('mt_product_status', array('id' => $rs['start_sid']));
            $rs['startName_en'] = $startStatus['name_en'];
            $rs['startName_es'] = $startStatus['name_es'];
            $rs['startName_ch'] = $startStatus['name_ch'];
            $endStatus = $this->common_model->selectFirst('mt_product_status', array('id' => $rs['end_sid']));
            $rs['endName_en'] = $endStatus['name_en'];
            $rs['endName_es'] = $endStatus['name_es'];
            $rs['endName_ch'] = $endStatus['name_ch'];

            $rs['is_sync'] = $rs['is_sync'] ? 'Yes' : 'No';
            $rs['add_time'] = date('Y-m-d H:i:s', $rs['add_time']);
        }
        unset($rs);
        //#配件
        $partsList = $this->common_model->selectCustom('mt_product_parts', array('pid' => $id));
        foreach ($partsList as &$rs) {
            if ($rs['status'] == 2) {
                $rs['statusName'] = 'pending';
            } elseif ($rs['status'] == 3) {
                $rs['statusName'] = 'wait purchase';
            } else {
                $rs['statusName'] = 'Normal';
            }

            if ($orderFirst['merchant_num'] == '1028') {
	    
	    	$rs['price']=number_format($rs['price']*$currency['rate'], 2, '.', '');
                $rs['price'] = number_format(currency_service($rs['currency'], 'CNY', $rs['price']), 2, '.', '');
                $rs['rate_price'] = number_format( $rs['rate_price']*$currency['rate'], 2, '.', '');

            } else {
                $rs['price'] = $rs['price'] . ' ' . $rs['currency'];
                $rs['rate_price'] = $rs['rate_price'] . ' ' . $orderFirst['currency_code'];
            }
        }
        unset($rs);
        if ($orderFirst['merchant_num'] == '1028') {
          
		//产品详情 -> 产品信息 -> 费用总计
	
		$productFirst['totalAmount']=number_format($productFirst['totalAmount']*$currency['rate'], 2, '.', '');
		
		$orderFirst['currency_code'] = 'CNY';
        }
        //#产品信息
        $data['productFirst'] = $productFirst;
        $data['orderFirst'] = $orderFirst;
        $data['brandCustomer'] = $brandCustomer;
        $data['trackList'] = $trackList;
        $data['faultList'] = $faultList;
        $data['accessoriesList'] = $accessoriesList;
        $data['repairItemList'] = $repairItemList;
        $data['partsList'] = $partsList;

        $message = 'successful';
        $status = 1;
        json_output($data, $message, $status);

    }

}
